package com.redis.template;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author jinYuLinLang
 * @version 1.0.0
 * @ClassName JedisCLusterTemplate.java
 * @Description <p></p>
 * @createTime 2024-08-29 19:52:00
 */
public class JedisCLusterTemplate extends MyRedisTemplate {

    private JedisCluster JEDIS_CLUSTER;

    protected JedisCLusterTemplate(String host, String username, String password) {
        String[] split = host.split(",");
        Set<HostAndPort> nodes = new HashSet<>();
        for (String ipPort : split) {
            String[] ipPorts = ipPort.split(":");
            nodes.add(new HostAndPort(ipPorts[0], Integer.parseInt(ipPorts[1])));
        }
        if (username != null && password != null) {
            JEDIS_CLUSTER = new JedisCluster(nodes, username, password);
        } else {

            JEDIS_CLUSTER = new JedisCluster(nodes);
        }
    }


    @Override
    public String get(String key) {
        return JEDIS_CLUSTER.get(key);
    }

    @Override
    public String set(String key, String value, TimeUnit timeUnit, long expire) {
        long seconds = timeUnit.toSeconds(expire);
        try {
            return JEDIS_CLUSTER.set(key, value);
        } finally {
            JEDIS_CLUSTER.expire(key, seconds);
        }
    }

    @Override
    public String set(String key, String value) {
        return JEDIS_CLUSTER.set(key, value);
    }

    @Override
    public Long del(String key) {
        return JEDIS_CLUSTER.del(key);
    }


    @Override
    public Long append(String key, String value) {
        return JEDIS_CLUSTER.append(key, value);
    }

    @Override
    public Boolean exists(String key) {
        return JEDIS_CLUSTER.exists(key);
    }

    @Override
    public Long expire(String key, long seconds) {
        return JEDIS_CLUSTER.expire(key, seconds);
    }

    @Override
    public Long ttl(String key) {
        return JEDIS_CLUSTER.ttl(key);
    }

    @Override
    public void close() {
        if (JEDIS_CLUSTER != null) {
            JEDIS_CLUSTER.close();
        }
    }
}
